package com.lyx.materialdesigndemo.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.ButtonBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;

import com.lyx.materialdesigndemo.R;
import com.lyx.materialdesigndemo.adapter.ComFragmentAdapter;
import com.lyx.materialdesigndemo.base.BaseActivity;
import com.lyx.materialdesigndemo.fragment.ArticleFragment;
import com.lyx.materialdesigndemo.fragment.DynamicFragment;
import com.lyx.materialdesigndemo.fragment.QuestionFragment;
import com.lyx.materialdesigndemo.util.ScreenUtil;
import com.lyx.materialdesigndemo.util.StatusBarUtil;
import com.lyx.materialdesigndemo.view.ColorFlipPagerTitleView;
import com.lyx.materialdesigndemo.view.JudgeNestedScrollView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;
import com.scwang.smartrefresh.layout.util.DensityUtil;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class OneActivity extends BaseActivity {

    private Toolbar mToolBar;
    private SmartRefreshLayout mRefreshLayout;
    private ViewPager mViewPager;
    private MagicIndicator mMagicIndicator;
    private JudgeNestedScrollView mScrollView;
    private MagicIndicator mMagicIndicatorTitle;
    private ButtonBarLayout mButtonBarLayout;
    private ImageView mIvHeader;
    private ImageView mIvBack;
    private ImageView mIvMenu;

    int toolBarPositionY = 0;
    private int mOffset = 0;
    private int mScrollY = 0;
    private String[] mTitles = new String[]{"动态", "文章", "问答"};
    private List<String> mDataList = Arrays.asList(mTitles);

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, OneActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int setLayoutId() {
        return R.layout.acitivity_one;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        init();
        StatusBarUtil.immersive(this);
        StatusBarUtil.setPaddingSmart(this, mToolBar);
        mRefreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onHeaderPulling(RefreshHeader header, float percent, int offset, int bottomHeight, int extendHeight) {
                mOffset = offset / 2;
                mIvHeader.setTranslationY(mOffset - mScrollY);
                mToolBar.setAlpha(1 - Math.min(percent, 1));
            }

            @Override
            public void onHeaderReleasing(RefreshHeader header, float percent, int offset, int bottomHeight, int extendHeight) {
                mOffset = offset / 2;
                mIvHeader.setTranslationY(mOffset - mScrollY);
                mToolBar.setAlpha(1 - Math.min(percent, 1));
            }
        });
        mToolBar.post(new Runnable() {
            @Override
            public void run() {
                dealWithViewPager();
            }
        });
        mScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            int lastScrollY = 0;
            int h = DensityUtil.dp2px(170);
            int color = ContextCompat.getColor(getApplicationContext(), R.color.mainWhite) & 0x00ffffff;

            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int[] location = new int[2];
                mMagicIndicator.getLocationOnScreen(location);
                int yPosition = location[1];
                if (yPosition < toolBarPositionY) {
                    mMagicIndicatorTitle.setVisibility(View.VISIBLE);
                    mScrollView.setNeedScroll(false);
                } else {
                    mMagicIndicatorTitle.setVisibility(View.GONE);
                    mScrollView.setNeedScroll(true);

                }

                if (lastScrollY < h) {
                    scrollY = Math.min(h, scrollY);
                    mScrollY = scrollY > h ? h : scrollY;
                    mButtonBarLayout.setAlpha(1f * mScrollY / h);
                    mToolBar.setBackgroundColor(((255 * mScrollY / h) << 24) | color);
                    mIvHeader.setTranslationY(mOffset - mScrollY);
                }
                if (scrollY == 0) {
                    mIvBack.setImageResource(R.drawable.back_white);
                    mIvMenu.setImageResource(R.drawable.icon_menu_white);
                } else {
                    mIvBack.setImageResource(R.drawable.back_black);
                    mIvMenu.setImageResource(R.drawable.icon_menu_black);
                }

                lastScrollY = scrollY;
            }
        });
        mButtonBarLayout.setAlpha(0);
        mToolBar.setBackgroundColor(0);


        mViewPager.setAdapter(new ComFragmentAdapter(getSupportFragmentManager(), getFragments()));
        mViewPager.setOffscreenPageLimit(10);
        initMagicIndicator();
        initMagicIndicatorTitle();
    }

    @Override
    public void initData() {

    }

    private void init() {
        mToolBar = findViewById(R.id.toolbar);
        mRefreshLayout = findViewById(R.id.refreshLayout);
        mViewPager = findViewById(R.id.view_pager);
        mMagicIndicator = findViewById(R.id.magic_indicator);
        mScrollView = findViewById(R.id.scrollView);
        mMagicIndicatorTitle = findViewById(R.id.magic_indicator_title);
        mButtonBarLayout = findViewById(R.id.buttonBarLayout);
        mIvHeader = findViewById(R.id.iv_header);
        mIvBack = findViewById(R.id.iv_back);
        mIvMenu = findViewById(R.id.iv_menu);
    }

    private void dealWithViewPager() {
        toolBarPositionY = mToolBar.getHeight();
        ViewGroup.LayoutParams params = mViewPager.getLayoutParams();
        params.height = ScreenUtil.getScreenHeightPx(getApplicationContext()) - toolBarPositionY - mMagicIndicator.getHeight() + 1;
    }

    private List<Fragment> getFragments() {
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(DynamicFragment.getInstance());
        fragments.add(ArticleFragment.getInstance());
        fragments.add(QuestionFragment.getInstance());
        return fragments;
    }

    private void initMagicIndicator() {
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setScrollPivotX(0.65f);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorFlipPagerTitleView(context);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setNormalColor(ContextCompat.getColor(OneActivity.this, R.color.mainBlack));
                simplePagerTitleView.setSelectedColor(ContextCompat.getColor(OneActivity.this, R.color.mainBlack));
                simplePagerTitleView.setTextSize(16);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index, false);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(UIUtil.dip2px(context, 2));
                indicator.setLineWidth(UIUtil.dip2px(context, 20));
                indicator.setRoundRadius(UIUtil.dip2px(context, 3));
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setColors(ContextCompat.getColor(OneActivity.this, R.color.mainRed));
                return indicator;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mMagicIndicator, mViewPager);
    }

    private void initMagicIndicatorTitle() {
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setScrollPivotX(0.65f);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorFlipPagerTitleView(context);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setNormalColor(ContextCompat.getColor(OneActivity.this, R.color.mainBlack));
                simplePagerTitleView.setSelectedColor(ContextCompat.getColor(OneActivity.this, R.color.mainBlack));
                simplePagerTitleView.setTextSize(16);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index, false);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(UIUtil.dip2px(context, 2));
                indicator.setLineWidth(UIUtil.dip2px(context, 20));
                indicator.setRoundRadius(UIUtil.dip2px(context, 3));
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setColors(ContextCompat.getColor(OneActivity.this, R.color.mainRed));
                return indicator;
            }
        });
        mMagicIndicatorTitle.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mMagicIndicatorTitle, mViewPager);
    }

//    @OnClick({R.id.tv_username, R.id.iv_avatar, R.id.tv_authentication, R.id.tv_edit_info, R.id.tv_position})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.tv_username:
//                toast("SiberiaDante");
//                break;
//            case R.id.iv_avatar:
//                toast("头像");
//                break;
//            case R.id.tv_authentication:
//                toast("头衔认证");
//                break;
//            case R.id.tv_edit_info:
//                toast("编辑资料");
//                break;
//            case R.id.tv_position:
//                toast("中国·GitHub");
//                break;
//        }
//    }
//
//    private void toast(String msg) {
//        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
//    }

}
